//
//  TableOperation.m
//  Runone
//
//  Created by runone01 on 16/8/18.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "TableOperation.h"
#import "FMDBOperation.h"
#import "HighWayRoadRecord.h"
#import "AppDelegate.h"
#import "StationModel.h"
#import "DeviceBaseInfo.h"
#import "PileInfo.h"
#import "UpdateModel.h"
#import "AllLastestVehicleDynamic.h"

#import "HighwayMergeRoadRecordModel.h"

@implementation TableOperation
{
    FMDBOperation *_dbService;
}

+ (instancetype)shareInstance
{
    static id instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

//初始化路径
- (instancetype)init
{
    if (self = [super init]) {
        NSString *dbName = @"people2.db";
        NSString *directory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSString *dbPath = [directory stringByAppendingPathComponent:dbName];
        _dbService = [[FMDBOperation alloc] initWithPath:dbPath];
        
    }
    return self;
}


// **************************************************** -新的高速干道Begin- ****************************************************

//创建新的高速干道信息表
- (void)creatNewAllHighWayRoadTable {
    NSString *sql=@"CREATE TABLE if not exists AllNewHighWayRoadTable(RoadUID text CONSTRAINT PK_OFFLINE_SYSUSER PRIMARY KEY,SystemUID text,RoadCode text,RoadName TEXT,RoadType text,BeginPileNo TEXT,BeginPileDistance TEXT,EndPileNo TEXT,EndPileDistance TEXT)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"NewAllHighWayRoadTable成功");
    }else {
        NSLog(@"NewAllHighWayRoadTable 失败");
    }
}
//获得新的高速干道信息表
- (NSArray *)getNewAllHighWayRoadTable {
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"AllNewHighWayRoadTable" ModelClass:[HighwayMergeRoadRecordModel class]];
    return people;
}
//@property (nonatomic, assign)   NSInteger       mergeType;    //  0起始/结束位置1收费站2交通枢纽
//@property (nonatomic, copy)     NSString        *mergeName;   // 路段流水号
//@property (nonatomic, strong)   MergeJsonModel  *mergeJson;   // 路段方向值
//@property (nonatomic, assign)   NSInteger       Distance;     // 路段方向描述
//
//@property (nonatomic, strong) NSArray  *UpWayDevices;      //上行设备
//@property (nonatomic, strong) NSArray *DownWayDevices;     //下行设备
//@property (nonatomic, strong) NSArray *mergeJsonArray;     //枢纽 //LineMergeJsonModel

// 创建新的高速干道中的收费站和交通枢纽信息表
-  (void) creatNewAllHighStationTable {
//    NSString *sql = @"CREATE TABLE if no exists NewAllHighStationTable(mergeType INTEGER, mergeName TEXT, Distance INTEGER, FOREIGN KEY(trackartist) REFERENCES artist(artistid)
//    );"
}

//获取新的高速干道中的收费站和交通枢纽信息表
//- (NSArray *)getNewAllHighStationTable {
//
//}

// **************************************************** -新的高速干道End- ****************************************************

//创建收费站信息表
-(void)createStationTable
{
    NSString *sql=@"CREATE TABLE if not exists StationTable(TollStationUID text CONSTRAINT PK_OFFLINE_SYSUSER PRIMARY KEY,SystemUID text,RoadUID text,TollStationName TEXT,PileNo text,PileDistance integer,IsTwoWayPay integer,Longitude text,Latitude text,EntranceLaneCount integer,ExitLaneCount integer,ETCEntranceCount integer,ETCExitCount integer,VideoSetting text,SystemCode text,Distance integer)";
   // NSString *sql=@"create table if not exists Test_student(NameID nvarchar(100) primary key autoincrement,name text,age integer)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"创建StationTable完毕");
    }
    else
    {
        NSLog(@"创建StationTable错误");
    }
}




//创建桩号信息表
-(void)createPirNoTable
{
    NSString *sql = @"CREATE TABLE PirNoTable (PileUID TEXT PRIMARY KEY, SystemUID TEXT,RoadUID TEXT,PileNo text,Longitude text,Latitude text,SystemCode text,RoadName text,RoadType text,LeftLongitude text,LeftLatitude text,RightLongitude text,RightLatitude text)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"创建PirNoTable完毕");
    }
    else
    {
        NSLog(@"创建PirNoTable错误");
    }
}

//创建更新时间表
-(void)createUpdateTimeTable
{
    
    NSString *sql = @"CREATE TABLE UpdateTimeTable (RecordUID TEXT PRIMARY KEY, SystemUID TEXT,DataDescription TEXT,DataCode integer,DataChangeTime text,SystemCode text)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"创建UpdateTimeTable完毕");
    }
    else
    {
        NSLog(@"创建UpdateTimeTable错误");
    }
}

//@property(nonatomic,copy)NSString *DeviceUID;//设备流水号
//@property(nonatomic,copy)NSString *SystemUID;//系统流水号
//@property(nonatomic,copy)NSString *RoadUID;//干道流水号
//@property(assign, nonatomic)NSInteger DeviceType;//设备类型
//@property(nonatomic,copy)NSString *SerialNumber;//设备序列表
//@property(nonatomic,copy)NSString *RegionUID;//路段流水号
//@property(assign, nonatomic)NSInteger Direction;//路段方向
//@property(nonatomic,copy)NSString *PileNo;//桩号
//@property(assign, nonatomic)NSInteger PileDistance;//桩距离
//@property(nonatomic,copy)NSString *DeviceMode;//设备型号
//@property(nonatomic)CGFloat Longitude;//经度
//@property(nonatomic)CGFloat Latitude;//纬度

//@property(nonatomic,copy)NSString *SystemCode;//系统编码
//@property(nonatomic,copy)NSString *RegionName;//路段名称
//@property(assign, nonatomic)NSString *Distance;//桩号+桩距离
//@property (nonatomic,strong) VideoSetting *setModel;
//@property (nonatomic, strong)NSString  *DirectionName; //新增的 根据该字段直接获得方向

//创建设备信息表
- (void)createAllDeviceTable {
    
    NSString *sql = @"CREATE TABLE AllDeviceTable (DeviceUID TEXT  PRIMARY KEY, SystemUID TEXT, RoadUID text, DeviceType TEXT, SerialNumber TEXT, RegionUID TEXT, Direction TEXT, PileNo TEXT,PileDistance TEXT, DeviceMode TEXT, Longitude TEXT,Latitude TEXT,SystemCode TEXT,RegionName TEXT,Distance TEXT,DirectionName TEXT)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"创建AllDeviceTable完毕");
    }
    else
    {
        NSLog(@"创建AllDeviceTable错误");
    }
}

-(void)createCarTable
{
    NSString *sql = @"CREATE TABLE CarTable (UID TEXT  PRIMARY KEY,RoadUID TEXT,CollectedRecordUID text,AccessCode INTEGER,TransType TEXT,MCUID INTEGER,VehicleNo INTEGER,Color TEXT,Cur_AccessCode INTEGER,Online_flg INTEGER,Warn_flg INTEGER,Status_flg INTEGER,Latitude INTEGER,Longitude TEXT,Elevation INTEGER,OD_Rate TEXT,Locator_Rate text,Mileage text,Direction text,DateTime_Position_Time TEXT,DateTime_RecvTime TEXT,SystemUID TEXT,SystemCode TEXT)";
    BOOL creat = [_dbService executeUpdate:sql param:nil];
    if (creat) {
        NSLog(@"创建CarTable完毕");
    }
    else
    {
        NSLog(@"创建CarTable错误");
    }
}

#pragma mark -----------------------------对表的操作---------------------------
//插入数据
- (void)insertDataToTableName:(NSString *)sql Data:(NSArray *)dataArray {
    //    NSString *sql = @"insert into TestTable2(RoadUID, SystemUID) values(?,?)";
    //    NSArray *param = @[@80, @"male"];
    //
    //    NSString *text = @"dataValue";
    //    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    
    BOOL res=[_dbService executeUpdate:sql param:dataArray];
    if (res) {
        NSLog(@"插入数据成功");
    }
    else
    {
        NSLog(@"插入数据失败");
    }
}

//更新表
-(void)updateTable:(NSString *)sql Param:(NSArray *)param
{
//    NSString * update = [NSString stringWithFormat:@"update FlightGoods set actualNum = '%@', loseNum = '%@',remarks = '%@' where goodsCode = '%@'",flightGoods.actualNum,flightGoods.loseNum,flightGoods.remarks,flightGoods.goodsCode];

    BOOL res=[_dbService executeUpdate:sql param:param];
    if (res) {
        NSLog(@"更新成功");
    }
    else
    {
        NSLog(@"更新失败");
    }
}
//查询
- (NSArray *)queryFromTableName:(NSString *)TableName ModelClass:(Class)modelClass
{
    NSString *str=[NSString stringWithFormat:@"select * from %@",TableName];
    NSArray *queryArray =[_dbService executeQuery:str withArgumentsInArray:nil modelClass:[modelClass class]];
    return queryArray;
}

- (NSArray *)queryFromTableName:(NSString *)TableName Row:(NSString *)row ModelClass:(Class)modelClass
{
    NSString *str=[NSString stringWithFormat:@"select * from %@ where PileNo = '%@'",TableName,row];
    NSArray *queryArray =[_dbService executeQuery:str withArgumentsInArray:nil modelClass:[modelClass class]];  
    return queryArray;
}
//删除
-(BOOL)deleteTable:(NSString *)TableName
{
    NSString *delete=[NSString stringWithFormat:@"DROP TABLE %@",TableName];
    BOOL res = [_dbService executeUpdate:delete param:nil];
    if (res) {
        NSLog(@"删除表成功");
    }
    else
    {
        NSLog(@"删除失败");
    }
    return res;
}

#pragma mark ---------------------------获取收费信息表------------------------
-(NSArray *)getStationTableData
{
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"StationTable" ModelClass:[StationModel class]];
    for (StationModel *person in people)
    {
        NSLog(@"%@,%@,%@,%@,%@,%ld,%ld,%ld,%ld,%@,%@,%ld",person.TollStationUID,person.SystemUID,person.RoadUID,person.TollStationName,person.PileNo,(long)person.PileDistance,(long)person.ExitLaneCount,(long)person.ETCEntranceCount,(long)person.ETCExitCount,person.VideoSetting,person.SystemCode,(long)person.Distance);
    }
    return people;
}

#pragma mark ---------------------------获取设备信息表------------------------
-(NSArray *)getAllDeviceTable {
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"AllDeviceTable" ModelClass:[DeviceBaseInfo class]];
    return people;
}

#pragma mark ---------------------------获取桩号信息表------------------------
-(NSArray *)getePirNoTable
{
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"PirNoTable" ModelClass:[PileInfo class]];
    //PileUID, SystemUID,RoadUID,PileNo,Longitude,Latitude,SystemCode,RoadName,RoadType
    for (PileInfo *person in people) {
        NSLog(@"PileUID=%@, SystemUID=%@,RoadUID=%@,PileNo=%ld,Longitude=%f,Latitude=%f,SystemCode=%ld,RoadName=%@,RoadType=%ld", person.PileUID,person.SystemUID,person.RoadUID,(long)person.PileNo,person.Longitude,person.Latitude,(long)person.
              SystemCode,person.RoadName,(long)person.RoadType);
    }
    NSLog(@"%lu",(unsigned long)people.count);
    return people;
}

-(NSArray *)getePirNoTableOfRow:(NSString *)row
{
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"PirNoTable" Row:row ModelClass:[PileInfo class]];
    //PileUID, SystemUID,RoadUID,PileNo,Longitude,Latitude,SystemCode,RoadName,RoadType
    for (PileInfo *person in people) {
        NSLog(@"PileNo=%ld,Longitude=%f,Latitude=%f,RoadName=%@,RoadType=%ld",(long)person.PileNo,person.Longitude,person.Latitude,person.RoadName,(long)person.RoadType);
    }
    NSLog(@"%lu",(unsigned long)people.count);
    return people;
}

#pragma mark ---------------------------获取更新时间信息表------------------------
-(NSArray *)getUpdateTimeTable
{
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"UpdateTimeTable" ModelClass:[UpdateModel class]];
    //RecordUID , SystemUID ,DataDescription ,DataCode ,DataChangeTime ,SystemCode
    for (UpdateModel *person in people) {
        NSLog(@"RecordUID=%@, SystemUID=%@,DataDescription=%@,DataCode=%ld,DataChangeTime=%@,SystemCode=%@", person.RecordUID,person.SystemUID,person.DataDescription,(long)person.DataCode,person.DataChangeTime,person.SystemCode);
    }
    
    return people;
}

#pragma mark ---------------------------获取两客一危信息表------------------------
-(NSArray *)getCarTable
{
    //UID,CollectedRecordUID,AccessCode,TransType,MCUID,VehicleNo,Color,Cur_AccessCode ,Online_flg ,Warn_flg ,Status_flg,Latitude,Longitude ,Elevation,OD_Rate ,Locator_Rate,Mileage,Direction,DateTime_Position_Time,DateTime_RecvTime,SystemUID,SystemCode
    NSArray *people = [[TableOperation shareInstance] queryFromTableName:@"CarTable" ModelClass:[AllLastestVehicleDynamic class]];
    //RecordUID , SystemUID ,DataDescription ,DataCode ,DataChangeTime ,SystemCode
    for (AllLastestVehicleDynamic *person in people) {
        NSLog(@"UID=%@, CollectedRecordUID=%@,AccessCode=%ld,TransType=%@,MCUID=%@,VehicleNo=%@,Color=%ld,Cur_AccessCode=%ld,Online_flg=%ld,Warn_flg=%ld,Status_flg=%ld,Latitude=%f,Longitude=%f,Elevation=%f,OD_Rate=%ld,Locator_Rate=%ld,Mileage=%ld,Direction=%@,DateTime_Position_Time=%@,DateTime_RecvTime=%@,SystemUID=%@,SystemCode=%@", person.UID,person.CollectedRecordUID,(long)person.AccessCode,person.TransType,person.MCUID,person.VehicleNo,(long)person.Color,(long)person.Cur_AccessCode,(long)person.Online_flg,(long)person.Warn_flg,(long)person.Status_flg,person.Latitude,person.Longitude,person.Elevation,(long)person.OD_Rate,(long)person.Locator_Rate,(long)person.Mileage,person.Direction,person.DateTime_Position_Time,person.DateTime_RecvTime,person.SystemUID,person.SystemCode);
    }
    return people;
}

#pragma mark ---------------------------更新表------------------------

//
-(void)updateTable:(NSString *)sql;
{
    
    [self updateTable:sql Param:nil];
    
}



@end
